//
//  YWMeterReadingDetailRecordTableViewController.m
//  maintain
//
//  Created by Kyo on 16/8/19.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWMeterReadingDetailRecordTableViewController.h"
#import "YWModifyMeterReadingTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"

//#import "YWImageView.h"
#import "YWPhotoView.h"
#import "YWCommonTool.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "MBProgressHUD.h"

#import "YWMeterReadingDetailRecordCell.h"
#import "YWLocationCell.h"

#import "YWMeterReadingManager.h"
#import "YWEquipmentManager.h"
#import "YWBuildingManager.h"

@interface YWMeterReadingDetailRecordTableViewController ()<UITextFieldDelegate>
@property (nonatomic,strong) NSMutableArray *dateSource;
@property (nonatomic, strong) UIView *pictureView;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, weak) MBProgressHUD* HUD;
@end

@implementation YWMeterReadingDetailRecordTableViewController
- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"记录详情";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    if (_isFromWaitReadVC) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"修改" style:UIBarButtonItemStylePlain target:self action:@selector(modifyLastReadNumber)];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(referenceTableView:) name:KModifyMeterReadSuccessNotification object:nil];
    [self.tableView registerClass:[YWMeterReadingDetailRecordCell class] forCellReuseIdentifier:YWMeterReadingDetailRecordCellIdentifier];
    [self.tableView registerClass:[YWLocationCell class] forCellReuseIdentifier:YWLocationCellIdentifier];
    self.tableView.tableFooterView = self.footView;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (void)referenceTableView:(NSNotification*)noti{
    self.meterReadingRecord = noti.userInfo[@"meterReadingRecord"];
    _dateSource = nil;
    [self.tableView reloadData];
}

- (NSMutableArray *)dateSource{
    if (!_dateSource) {
        _dateSource = [NSMutableArray array];
        
        [_dateSource addObject:[self equipmentName]];
        [_dateSource addObject:[self ownCode]];
        [_dateSource addObject:[self rate]];
        [_dateSource addObject:[self companyName]];
        [_dateSource addObject:[self place]];
        [_dateSource addObject:[self readingTime]];
        [_dateSource addObject:[self thisReadNumber]];
        [_dateSource addObject:[self useNumberText]];
        [_dateSource addObject:[self monthLabel]];
        [_dateSource addObject:[self notoLabel]];
    }
    return _dateSource;
}

- (NSString *)equipmentName{
    YWEquipment *equipment = [[YWEquipmentManager shareManager]equipmentWithId:self.meterReadingRecord.equipmentId];
    NSString *equipmentName = [NSString stringWithFormat:@"设备名称: %@",equipment.equipmentName?:@""];
    return equipmentName;
}

- (NSString *)ownCode{
    YWEquipment *equipment = [[YWEquipmentManager shareManager]equipmentWithId:self.meterReadingRecord.equipmentId];
    NSString * ownCode = [NSString stringWithFormat:@"表号: %@",equipment.ownCode?:@"无"];
    return ownCode;
}

- (NSString *)rate{
    NSString * rate = [NSString stringWithFormat:@"倍率: %.1f",self.meterReadingRecord.rate>0?self.meterReadingRecord.rate:1.0];
    return rate;
}

- (NSString *)companyName{
   YWMeterProperty *meterProperty = [[YWEquipmentManager shareManager] meterPropertyWithEquipmentId:self.meterReadingRecord.equipmentId];
    NSString * companyName = [NSString stringWithFormat:@"单位名称: %@",meterProperty.companyName.length ? meterProperty.companyName:@"无"];
    return companyName;
}

- (NSString *)place{
    YWMeterProperty *meterProperty = [[YWEquipmentManager shareManager] meterPropertyWithEquipmentId:self.meterReadingRecord.equipmentId];
    NSString * place = [NSString stringWithFormat:@"房号: %@",meterProperty.place.length ? meterProperty.place:@"无"];
    return place;
}

- (NSString *)readingTime{
    NSString *recordTime = [YWCommonTool showFullTime:self.meterReadingRecord.readingTime/1000];
    NSString * readingTime = [NSString stringWithFormat:@"抄表时间: %@",recordTime];
    return readingTime;
}

- (NSString *)thisReadNumber{
    NSString * thisReadNumber = [NSString stringWithFormat:@"本次读数: %.2f",self.meterReadingRecord.thisReadNumber];
    return thisReadNumber;
}

- (NSString *)useNumberText{
    CGFloat useNumber = self.meterReadingRecord.usedAmount;
    NSInteger wEquipmentTypeId = [[YWMeterReadingManager shareManager]waterMeterEquipmentTypeId];
    NSInteger eEquipmentTypeId = [[YWMeterReadingManager shareManager]electricMeterEquipmentTypeId];
    NSInteger gEquipmentTypeId = [[YWMeterReadingManager shareManager]gasMeterEquipmentTypeId];
    if (self.meterReadingRecord.equipmentTypeId == wEquipmentTypeId) {
        NSString * useNumberText = useNumber>0?[NSString stringWithFormat:@"本次用水量: %.2f立方米",useNumber]:@"本次用水量: -";
        return useNumberText;
    }else if (self.meterReadingRecord.equipmentTypeId == eEquipmentTypeId) {
        NSString * useNumberText = useNumber>0?[NSString stringWithFormat:@"本次用电量: %.2f度",useNumber]:@"本次用电量: -";
        return useNumberText;
    }else if (self.meterReadingRecord.equipmentTypeId == gEquipmentTypeId) {
        NSString * useNumberText = useNumber>0?[NSString stringWithFormat:@"本次用气量: %.2f立方米",useNumber]:@"本次用气量: -";
        return useNumberText;
    }else{
        NSString * useNumberText = useNumber>0?[NSString stringWithFormat:@"本次用量: %.2f",useNumber]:@"本次用量: -";
        return useNumberText;
    }
}

- (NSString *)monthLabel{
    NSString * monthLabel = [NSString stringWithFormat:@"抄表月份: %@",self.meterReadingRecord.readingMonth?:@"未填写"];
    return monthLabel;
}

- (NSString *)notoLabel{
    NSString * notoLabel = [NSString stringWithFormat:@"备注: %@",self.meterReadingRecord.note.length?self.meterReadingRecord.note:@"未填写"];
    return notoLabel;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else{
        return self.dateSource.count;
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section == 0) {
//       return [tableView fd_heightForCellWithIdentifier:YWLocationCellIdentifier cacheByIndexPath:indexPath configuration:^(YWLocationCell *cell) {
//           [self configureLocationCell:cell atIndexPath:indexPath];
//        }];
//    }else{
//        CGFloat rowH = [tableView fd_heightForCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMeterReadingDetailRecordCell *cell) {
//            cell.contentLabel.text = self.dateSource[indexPath.row];
//        }];
//        return rowH>35?rowH:35;
//    }
//}

- (void)configureLocationCell:(YWLocationCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    YWEquipment *equipment = [[YWEquipmentManager shareManager]equipmentWithId:self.meterReadingRecord.equipmentId];
    cell.locationText = [[YWBuildingManager shareManager] equipmentLocation:equipment];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        
        YWLocationCell * cell = [tableView dequeueReusableCellWithIdentifier:YWLocationCellIdentifier];
        [self configureLocationCell:cell atIndexPath:indexPath];
        return cell;
        
    }else{
        YWMeterReadingDetailRecordCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier];
        cell.contentLabel.text = self.dateSource[indexPath.row];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

#pragma mark - tableview section foot view

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return nil;
    }else{
//        _pictureView,这样返回的值是空的
        return self.pictureView;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01;
    }else{
        return self.pictureView.frame.size.height;
    }
}

- (UIView *)pictureView{
    if (!_pictureView) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        _pictureView = view;
        CGFloat repairImageViewH = 0;
        NSArray *pictureArray = self.meterReadingRecord.pictures;
        if (pictureArray.count==0) {
            pictureArray = [[YWMeterReadingManager shareManager] recordPictureWithRecordId:self.meterReadingRecord.meterRecordId recordType:YWPictureRecordTypeMeterReading];
        }
        if (pictureArray.count>0) {
            YWPhotoView* imageV = [[YWPhotoView alloc] init];
            imageV.canAddPhoto = NO;
            imageV.photosArray = pictureArray;
            [imageV setFrame:CGRectMake(0, 10, imageV.frame.size.width, imageV.frame.size.height)];
            [_pictureView addSubview:imageV];
            repairImageViewH = imageV.frame.size.height+20;
        }
        [_pictureView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, repairImageViewH)];
    }
    return _pictureView;
}

- (UIView *)footView{
    if (!_footView) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80)];
        _footView = view;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH-15*2, 80)];
        label.backgroundColor = [UIColor customBackgroudColor];
        label.textColor = [UIColor customTextGrayBlackColor];
        label.numberOfLines = 0;
        label.font = kContentFont;
        label.text = @"请注意! 本次读数和上次读数为仪表终端读数,最终使用量需乘以倍率,实际水/电/煤气使用量为(本次读数-上次读数)*倍率";
        [_footView addSubview:label];
    }
    return _footView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)modifyLastReadNumber{
    NSTimeInterval timeJat = 7*24*60*60;
    NSDate* nowDate = [NSDate date];
    NSTimeInterval nowTime =[nowDate timeIntervalSince1970];
    BOOL isOverWeek = nowTime - (self.meterReadingRecord.readingTime)/1000 > timeJat ? YES : NO;
    if (isOverWeek) {
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:@"抄表时间已经超过一周，不能修改" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        YWModifyMeterReadingTableViewController *modifyMeterReadTVC = [[YWModifyMeterReadingTableViewController alloc] init];
        modifyMeterReadTVC.meterReadingRecord = self.meterReadingRecord;
        [self.navigationController pushViewController:modifyMeterReadTVC animated:YES];
//        UIAlertView* alrtView = [[UIAlertView alloc] initWithTitle:@"修改记录本次读数" message:@"该操作将会修改抄表记录的读数,请根据实际情况填写" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//        alrtView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
//        UITextField* modifyField = [alrtView textFieldAtIndex:0];
//        modifyField.clearButtonMode = UITextFieldViewModeWhileEditing;
//        modifyField.keyboardType = UIKeyboardTypeDecimalPad;
//        modifyField.placeholder = [NSString stringWithFormat:@"%.2f",self.meterReadingRecord.thisReadNumber];
//        modifyField.delegate = self;
//        UITextField* noteField = [alrtView textFieldAtIndex:1];
//        noteField.clearButtonMode = UITextFieldViewModeWhileEditing;
//        noteField.placeholder = [NSString stringWithFormat:@"备注: %@",self.meterReadingRecord.note.length?self.meterReadingRecord.note:@"无"];
////        [NSString stringWithFormat:@"",self.meterReadingRecord.thisReadNumber];
//        noteField.delegate = self;
//        [alrtView show];   
    }
}
/*
- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (!buttonIndex) {
        return;
    }
    if (buttonIndex == alertView.firstOtherButtonIndex) {
        [self.HUD show:YES];
        UITextField* modifyField = [alertView textFieldAtIndex:0];
        NSString *readNumberString = modifyField.text;
        [modifyField resignFirstResponder];
        UITextField* noteField = [alertView textFieldAtIndex:1];
        self.meterReadingRecord.note = noteField.text;
        [noteField resignFirstResponder];
        if ([readNumberString floatValue] < self.meterReadingRecord.thisReadNumber) {
            [self resetShowHUDWithText:@"读数不能小于上次记录读数"];
            [self.HUD hide:YES afterDelay:1.0];
            
        }else{
            self.meterReadingRecord.thisReadNumber = [readNumberString floatValue];
            self.meterReadingRecord.usedAmount = self.meterReadingRecord.thisReadNumber-self.meterReadingRecord.usedAmount;
            [[YWMeterReadingManager shareManager] modifyThisReadNumberOfMeterReadingRecord:self.meterReadingRecord withBlock:^(BOOL success) {
                if (success) {
                    [self resetShowHUDWithText:@"修改成功"];
                    self.dateSource = nil;
                    [self.tableView reloadData];
//                    self.thisReadingLabel.text = [NSString stringWithFormat:@"本次读数: %.2f",self.meterReadingRecord.thisReadNumber];
//                    self.useNumberLabel.text = [self useNumberText];
                }else{
                    [self resetShowHUDWithText:@"修改失败,请稍后重试"];
                }
                [self.HUD hide:YES afterDelay:0.5];
            }];
        }
    }
}
- (void)resetShowHUDWithText:(NSString*)text{
    self.HUD.mode = MBProgressHUDModeText;
    self.HUD.dimBackground = NO;
    self.HUD.labelText = text;
}
#define myDotNumbers @"0123456789.\n"
#define myNumbers @"0123456789\n"
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string

{
    NSCharacterSet* cs;
    NSUInteger nDotLoc = [textField.text rangeOfString:@"."].location;
    if (NSNotFound == nDotLoc && 0 != range.location) {
        cs = [[NSCharacterSet characterSetWithCharactersInString:myDotNumbers] invertedSet];
    }
    else {
        cs = [[NSCharacterSet characterSetWithCharactersInString:myNumbers] invertedSet];
    }
    NSString* filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basicTest = [string isEqualToString:filtered];
    if (!basicTest) {
        [YWCommonTool showTextHUDWithContent:@"输入内容无效"];
        return NO;
    }
    if (NSNotFound != nDotLoc && range.location > nDotLoc + 2) {
        [YWCommonTool showTextHUDWithContent:@"小数点后最多2位"];
        return NO;
    }
    
    //    NSString* text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    //    if (text.length > 0) {
    //        self.nextButton.enabled = YES;
    //    }
    //    else {
    //        self.nextButton.enabled = NO;
    //    }
    return YES;
}
*/
@end
